package fudan.se.project.service.infrastructure.entity.conference.post;

import fudan.se.project.domain.conference.post.Post;
import fudan.se.project.domain.conference.post.Rebuttal;
import fudan.se.project.domain.conference.production.ReviewInfo;
import fudan.se.project.repository.entity.conference.post.PostRepository;
import fudan.se.project.service.infrastructure.base.IEntityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Collection;

@Slf4j
@Service
public class PostService implements IEntityService<Post> {

    private final PostRepository postRepository;
    private final RebuttalService rebuttalService;

    public PostService(PostRepository postRepository, RebuttalService rebuttalService) {
        this.postRepository = postRepository;
        this.rebuttalService = rebuttalService;
    }

    public Post findByPaperIdNotInRebuttal(long id) {
        return postRepository.findByPaperIdNotInRebuttal(id);
    }

    public int countReplies(Post post) {
        return postRepository.countRepliesById(post.getId());
    }

    public boolean isPostReplied(ReviewInfo reviewInfo) {
        final Long paperId = reviewInfo.getPaper().getId();
        final Post post = this.findByPaperIdNotInRebuttal(paperId);
        final Rebuttal rebuttal = rebuttalService.findByPaperId(paperId);
        return
                (
                        reviewInfo.getVersion() == 0
                                && 0 != this.countReplies(post)
                ) || (
                        reviewInfo.getVersion() == 1
                                && rebuttal != null
                                && 0 != this.countReplies(rebuttal.getPost())
                );
    }

    @Override
    public Post findById(long id) {
        return postRepository.findById(id);
    }

    @Override
    public Post save(Post post) {
        return postRepository.save(post);
    }

    @Override
    public Iterable<Post> saveAll(Collection<Post> posts) {
        return postRepository.saveAll(posts);
    }
}
